import router from '../router'
import store from '../store'
import Config from '../utils/config.js'
import NProgress from 'nprogress'
import { APIGmallUserInfo, APIGetMallInfo } from '@/api/system.js'
// import Store2 from 'store2'

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (Object.keys(store.getters.userinfo).length && Object.keys(store.getters.mallinfo).length) {
        next()
      } else {
        APIGmallUserInfo()
          .then((res) => {
            // console.log('router:', store.getters.routers)
            // console.log('res.data.user.shop_ids.length:', res.data.user.shop_ids.length)
            // res.data.user.shop_ids = []
            // if (res.data.user.shop_ids.length === 0) {
            //   console.log('router:', 11111111111)
            //   next({ path: '/403' })
            // } else {
            store.commit('SET_USERINFO', res.data.user)
            store.commit('SET_MALLINFO', { shopIdList: res.data.user.shop_ids, shopNameList: res.data.user.shop_names })
            // 主体账号情况 手动commit role
            if (res.data.user.is_superuser) {
              store.commit('SET_ROLES', [0])
            } else {
              store.commit('SET_ROLES', [res.data.user.role_names[0]['rank']])
            }
            // }
          })
          .then(() => {
            // console.log('store.getters.userrole:', store.getters.userrole)
            store.dispatch('GenerateRoutes', { roles: store.getters.userrole }).then(() => { // 根据roles权限生成可访问的路由表
              router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            })
            store.dispatch('setmallId', Number(store.getters.userinfo.default_shop_id))
          })
          .then(() => {
            // console.log('store.getters.mallId:', store.getters.mallId)
            APIGetMallInfo(store.getters.mallId)
              .then((res) => {
                // console.log('res:', res)
                store.dispatch('setOpenningHours', res.data.shop.openning_hours)
                store.dispatch('setMallMapData', res.data.shop.zones)
                store.dispatch('setMallMapScale', res.data.shop.scale)
                store.dispatch('setMallMapBg', res.data.shop.ichnography)
                next({ ...to })
              })
          })
      }
    }
  } else {
    // 如果未设置白名单的话, 会出现死循环
    if (Config.NO_TOKEN_CANVIEW[to.path]) {
      next()
    } else {
      NProgress.done()
      next({ path: '/login' })
    }
  }
})
